package com.app.twth.net;


import com.app.twth.app.Constant;
import com.app.twth.app.MyApplication;
import com.app.twth.utils.LogUtil;
import com.app.twth.utils.PreferencesUtil;
import com.app.twth.utils.Utils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自定义拦截器
 * 打印日志
 */
public class LogInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;//打印请求异常信息
        try {
            Request.Builder requestBuilder = request.newBuilder();
            if (Utils.isEmpty(MyApplication.token)) {
                MyApplication.token = PreferencesUtil.getString(MyApplication.getAppInstance(), Constant.token);
            }
            if (!Utils.isEmpty(MyApplication.token)) {
                requestBuilder.addHeader("Access-Token", "" + MyApplication.token);
            }

            if (Utils.isEmpty(MyApplication.location)) {
                MyApplication.location = PreferencesUtil.getString(MyApplication.getAppInstance(), Constant.location);
            }
            if (!Utils.isEmpty(MyApplication.location)) {
                requestBuilder.addHeader("Current-Warehouse-Id", "" + MyApplication.location);
            }

            try {
                if (Utils.isEmpty(MyApplication.versionCode)) {
                    MyApplication.versionCode = Utils.getVersionName(MyApplication.getAppInstance());
                    requestBuilder.addHeader("app-version", MyApplication.versionCode);
                } else {
                    requestBuilder.addHeader("app-version", MyApplication.versionCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            response = chain.proceed(requestBuilder.build());
        } catch (Exception e) {
            LogUtil.d("HTTP", "网络请求异常\n" + e);
            throw e;
        }
        return response;
    }
}
